<template>
  <el-dialog :append-to-body="true" :close-on-click-modal="false" :before-close="cancel"
             :visible.sync="dialog" title="课程资源" append-to-body width="40%">
    <div class="el-dialog-div">
      <el-form ref="form" :model="resource" :rules="rules" size="small" label-width="120px">
        <el-form-item label="资源名称" prop="resourceName">
          <el-input v-model="resource.resourceName" maxlength="50" style="width: 370px;"/>
        </el-form-item>
        <el-form-item label="资源文件" prop="resourceFile">
          <el-upload
            class="upload-demo"
            drag
            :action="fileUploadUrl"
            :on-success="resourceHandleSuccess"
            :before-upload="beforeResource"
            :file-list="resourceFile">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          </el-upload>
        </el-form-item>
        <el-form-item label="课件学时" prop="classHour">
          <el-input v-model="resource.classHourStr" disabled placeholder="根据视频时长自动计算" controls-position="right"/>
        </el-form-item>
        <el-form-item label="是否允许下载" prop="cover">
          <el-switch
            v-model="resource.isDownload"
            :active-value="1"
            :inactive-value="0">
          </el-switch>
        </el-form-item>
      </el-form>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button type="text" @click="cancel">取消</el-button>
      <el-button :loading="loading" type="primary" @click="doSubmit">确认</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import { formatSeconds } from '@/utils/index'

  export default {
    data() {
      return {
        fileUploadUrl: process.env.FILE_UPLOAD,
        loading: false,
        dialog: false,
        edit: false,
        resourceFile: [],
        index: 0, //章节index
        resourceIndex: 0, //资源index
        resource: {
          chapterId: '',
          resourceName: '',
          resourceFile: '',
          resourceFileName: '',
          classHour: 0,
          classHourStr: '',
          sort: 0,
          isDownload: 1
        },
        rules: {
          resourceName: [
            { required: true, message: '请输入资源名称', trigger: 'blur' }
          ],
          resourceFile: [
            { required: true, message: '请上传课程资源', trigger: 'change' }
          ]
        }
      }
    },
    methods: {
      formatSeconds,
      cancel() {
        this.dialog = false
        this.resourceFile = []
        this.resource = {
          chapterId: '',
          resourceName: '',
          resourceFile: '',
          resourceFileName: '',
          classHour: 0,
          classHourStr: '',
          sort: 0,
          isDownload: 1
        }
      },
      doSubmit() {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            if (this.edit) {
              this.$emit('editSetResource', this.resource, this.index, this.resourceIndex)
            } else {
              this.$emit('setResource', this.resource, this.index)
            }
            this.cancel()
          }
        })
      },
      beforeResource(file) {
        const FILE_NAME = file.name
        if (FILE_NAME.substring(FILE_NAME.lastIndexOf('.')) !== '.mp4' &&
          FILE_NAME.substring(FILE_NAME.lastIndexOf('.')) !== '.MP4' &&
          FILE_NAME.substring(FILE_NAME.lastIndexOf('.')) !== '.avi' &&
          FILE_NAME.substring(FILE_NAME.lastIndexOf('.')) !== '.AVI') {
          this.$message.warning('仅支持.mp4.avi')
          return false
        }
      },
      resourceHandleSuccess(response, file, fileList) {
        this.resource.resourceFile = []
        const uploadFile = {
          name: file.name,
          url: file.response
        }
        this.resource.resourceFileName = file.name
        this.resource.resourceFile.push(uploadFile)
        this.resource.resourceFile = JSON.stringify(this.resource.resourceFile)
        this.$refs.form.validateField('resourceFile')
        this.handleTime(file.response).then(data => {
          let number = parseInt(data.toString())
          this.resource.classHour = number
          this.resource.classHourStr = formatSeconds(number)
        })
      },
      handleTime(url) {
        return new Promise((resolve, reject) => {
          let element = new Audio(url)
          element.addEventListener('loadedmetadata', () => {
            const time = Math.round(element.duration * 100) / 100
            resolve(time)
          })
          element.addEventListener('error', () => resolve(0))
        })
      }
    }
  }
</script>

<style scoped>
</style>
